﻿#ifdef _WIN32
#pragma execution_character_set("utf-8")
#endif

#include "widget.h"
#include "ui_widget.h"
#include "busidate.h"
#include <QDebug>
#include <QJsonParseError>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QSharedPointer>
#include <QDate>
#include <QIcon>
#include <QMessageBox>
#include <QDir>
#include <QTextStream>
#include <QTextCodec>


Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setWindowTitle("投保差异反馈明细");
    this->showMaximized();
    m_init_log();
    m_set_table_title();
    m_init_data();
    m_set_system_tray();
    ui->tableWidget->setMouseTracking(true);

}

Widget::~Widget()
{
    delete ui;
    if(m_sub_thread->isRunning())
    {
        m_sub_thread->exit();
        m_sub_thread->deleteLater();
    }
    if(m_loger.isOpen())
    {
        m_loger.close();
    }
}

//重写关闭函数
void Widget::closeEvent(QCloseEvent *e)
{
    e->ignore();
    this->hide();
}

//重写键盘释放函数
void Widget::keyReleaseEvent(QKeyEvent *event)
{
    event->ignore();
    if(event->key() == Qt::Key_F5)
    {
        if(m_enable_refresh)
        {
            m_write_log("手动执行页面刷新");
            m_write_log("请求监控数据");

            //请求数据
            emit perform_zjjk_check();

            //恢复刷新限制
            m_enable_refresh = false;

            //设置业务日期
            BusiDate m_date;
            ui->labelDate->setText(QString("业务日期：%1").arg(m_date.getBefThreeDate()));

            QMessageBox::information(this,"手动执行","手动更新数据成功","确  定");

            //1分钟后设置m_enable_refresh
            QTimer::singleShot(1000 * 60,this,[this]{m_enable_refresh = true;});
        }else
        {
            m_write_log("1分钟内不能重复手动执行");
            QMessageBox::information(this,"手动执行","1分钟内不能重复手动执行","确  定");
        }
    }
    if(event->key() == Qt::Key_Escape)
    {
        this->close();
    }

    /*
    if(event->key() == Qt::Key_F6)
    {
        if(m_enable_refresh)
        {
            m_write_log("手动执行信息交互数据刷新");
            m_write_log("请求监控数据");

            //请求数据
            emit perform_ask_check();            

            //恢复刷新限制
            m_enable_refresh = false;

            QMessageBox::information(this,"手动执行","手动执行信息交互数据刷新","确  定");

            //1分钟后设置m_enable_refresh
            QTimer::singleShot(1000 * 60,this,[this]{m_enable_refresh = true;});

        }else
        {
            m_write_log("1分钟内不能重复手动执行");
            QMessageBox::information(this,"手动执行","1分钟内不能重复手动执行","确  定");
        }
    }

    if(event->key() == Qt::Key_F7)
    {
        if(m_enable_refresh)
        {
            m_write_log("手动执行A13数据刷新");
            m_write_log("请求监控数据");

            //请求数据
            emit perform_note_check();

            //恢复刷新限制
            m_enable_refresh = false;

            QMessageBox::information(this,"手动执行","手动执行A13数据刷新","确  定");

            //1分钟后设置m_enable_refresh
            QTimer::singleShot(1000 * 60,this,[this]{m_enable_refresh = true;});

        }else
        {
            m_write_log("1分钟内不能重复手动执行");
            QMessageBox::information(this,"手动执行","1分钟内不能重复手动执行","确  定");
        }
    }
    */
}

//设置系统托盘
void Widget::m_set_system_tray()
{
    //设置系统托盘
    m_systemTray = new QSystemTrayIcon(this);
    m_systemTray->setIcon(QIcon(":/ICO/favicon16.ico"));
    m_systemTray->show();

    //系统托盘设置菜单
    m_systemTrayMenu = new QMenu(this);
    m_actionQuit = new QAction(m_systemTrayMenu);
    m_actionShowWindow = new QAction(m_systemTrayMenu);

    m_actionQuit->setText("退出");
    m_actionShowWindow->setText("显示窗口");

    //菜单增加动作
    m_systemTrayMenu->addAction(m_actionQuit);
    m_systemTrayMenu->addAction(m_actionShowWindow);

    //连接信号
    connect(m_actionQuit,&QAction::triggered,this,&Widget::m_Quit);
    connect(m_actionShowWindow,&QAction::triggered,this,&Widget::m_show_window);
    connect(m_systemTray,&QSystemTrayIcon::activated,this,&Widget::m_active_tray);

    m_systemTray->setContextMenu(m_systemTrayMenu);

    //设置标签
    m_systemTray->setToolTip("投保监控比对差异");

}

//设置表头
void Widget::m_set_table_title()
{
    //设置表头内容
    QStringList tableHeadString = {
        "比对差异类型",
        "比对差异数量",
        "反馈数量",
        "待核实",
        "待审核",
        "再核实",
        "审核结束"
    };
    ui->tableWidget->setColumnCount(tableHeadString.size());
    ui->tableWidget->setHorizontalHeaderLabels(tableHeadString);

    //设置表头自动扩张
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    //设置按行选择
    ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
    //设置各行变色
    ui->tableWidget->setAlternatingRowColors(true);
    //设置表格不能编辑
    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    //设置业务日期
    BusiDate m_date;
	int currentHour = QTime::currentTime().hour();    
	if(currentHour < 9)
	{
		ui->labelDate->setText(QString("业务日期：%1").arg(m_date.getBefThreeDate()));
	}else
	{
		ui->labelDate->setText(QString("业务日期：%1").arg(m_date.getEndDate()));
	}    
}

//设置数据
void Widget::m_init_data()
{
    m_sub_thread = new QThread(this);
    m_tbWorker = new tbWorker;
    m_timer_monitor = new QTimer(this);    
    m_tbWorker->moveToThread(m_sub_thread);
    m_sub_thread->start();
    connect(m_tbWorker,&tbWorker::send_zjjk_reply,this,&Widget::m_set_table_content);
    connect(m_tbWorker,&tbWorker::send_log,this,&Widget::m_write_log);
    connect(m_tbWorker,&tbWorker::send_error,this,&Widget::m_handleWorkerError);
    connect(m_timer_monitor,&QTimer::timeout,this,&Widget::m_time_out_monitor);
    connect(this,&Widget::start_check,m_tbWorker,&tbWorker::check);
    connect(this,&Widget::perform_zjjk_check,m_tbWorker,&tbWorker::get_zjjk_data);
    connect(this,&Widget::perform_ask_check,m_tbWorker,&tbWorker::get_ask_data);
    connect(this,&Widget::perform_a13_check,m_tbWorker,&tbWorker::get_a13_data);
    connect(this,&Widget::perform_note_check,m_tbWorker,&tbWorker::get_note_data);
    m_timer_monitor->start(1000 * 60);  //1分钟更新一次监控数据
    m_write_log("开始执行主程序");
    m_enable_refresh = true;

    //初始获取数据
    emit perform_zjjk_check();
}

//设置表格内容
void Widget::m_set_table_content(QByteArray reply)
{

    //解析QJsonDocument数据
    QByteArray json_array = reply.trimmed();
    if(!json_array.endsWith(']'))
    {
        int index = json_array.indexOf(']');
        json_array = json_array.mid(0,index);
    }

    QJsonDocument feed_back_json = QJsonDocument::fromJson(json_array);

    if(feed_back_json.isNull())
    {
        m_write_log("QJsonDocument解析失败");
        return;
    }

    //清空表格内容
    ui->tableWidget->clearContents();
    ui->tableWidget->setRowCount(0);

    QJsonArray feed_back_array = feed_back_json.array();
    for(int i = 0;i<feed_back_array.size();i++)
    {
        //整理数据
        QVariant temp = feed_back_array.at(i).toVariant();
        //插入记录
        auto tableRowNum = ui->tableWidget->rowCount();
        ui->tableWidget->insertRow(tableRowNum);
        ui->tableWidget->setItem(tableRowNum,0,new QTableWidgetItem(temp.toMap()["TABLE_DESC"].toString()));
        ui->tableWidget->setItem(tableRowNum,1,new QTableWidgetItem(temp.toMap()["NUM_BDCY"].toString()));
        ui->tableWidget->setItem(tableRowNum,2,new QTableWidgetItem(temp.toMap()["NUM_FK"].toString()));
        ui->tableWidget->setItem(tableRowNum,3,new QTableWidgetItem(temp.toMap()["NUM_DHS"].toString()));
        ui->tableWidget->setItem(tableRowNum,4,new QTableWidgetItem(temp.toMap()["NUM_DSH"].toString()));
        ui->tableWidget->setItem(tableRowNum,5,new QTableWidgetItem(temp.toMap()["NUM_ZHS"].toString()));
        ui->tableWidget->setItem(tableRowNum,6,new QTableWidgetItem(temp.toMap()["NUM_YSH"].toString()));

        //设置第一列内容
        ui->tableWidget->horizontalHeader()->setSectionResizeMode(0,QHeaderView::ResizeToContents);

        //设置内容居中
        ui->tableWidget->item(tableRowNum,1)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
        ui->tableWidget->item(tableRowNum,2)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
        ui->tableWidget->item(tableRowNum,3)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
        ui->tableWidget->item(tableRowNum,4)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
        ui->tableWidget->item(tableRowNum,5)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
        ui->tableWidget->item(tableRowNum,6)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);

        //设置警告颜色
        int dhsNum = temp.toMap()["NUM_DHS"].toInt();
        int zhsNum = temp.toMap()["NUM_ZHS"].toInt();
        if(dhsNum > 0 || zhsNum > 0)
        {
            //设置背景色
            ui->tableWidget->item(tableRowNum,0)->setBackgroundColor(QColor(255, 118, 117));
            ui->tableWidget->item(tableRowNum,1)->setBackgroundColor(QColor(255, 118, 117));
            ui->tableWidget->item(tableRowNum,2)->setBackgroundColor(QColor(255, 118, 117));
            ui->tableWidget->item(tableRowNum,3)->setBackgroundColor(QColor(255, 118, 117));
            ui->tableWidget->item(tableRowNum,4)->setBackgroundColor(QColor(255, 118, 117));
            ui->tableWidget->item(tableRowNum,5)->setBackgroundColor(QColor(255, 118, 117));
            ui->tableWidget->item(tableRowNum,6)->setBackgroundColor(QColor(255, 118, 117));

            //设置字体颜色
            ui->tableWidget->item(tableRowNum,0)->setTextColor(QColor(255, 255, 255));
            ui->tableWidget->item(tableRowNum,1)->setTextColor(QColor(255, 255, 255));
            ui->tableWidget->item(tableRowNum,2)->setTextColor(QColor(255, 255, 255));
            ui->tableWidget->item(tableRowNum,3)->setTextColor(QColor(255, 255, 255));
            ui->tableWidget->item(tableRowNum,4)->setTextColor(QColor(255, 255, 255));
            ui->tableWidget->item(tableRowNum,5)->setTextColor(QColor(255, 255, 255));
            ui->tableWidget->item(tableRowNum,6)->setTextColor(QColor(255, 255, 255));
        }
    }
}

//退出
void Widget::m_Quit()
{
    auto select = QMessageBox::information(this,"关闭窗口","确认是否退出投保监控","取  消","确  定");
    if(select == 1)
    {
        QApplication::exit(0);
    }
}

//窗口最大化
void Widget::m_show_window()
{
    if(this->isHidden() || this->isMinimized())
    {
        this->showMaximized();
    }   
}

//双击或单击系统托盘槽函数
void Widget::m_active_tray(QSystemTrayIcon::ActivationReason reason)
{
    if(reason == QSystemTrayIcon::DoubleClick ||
        reason == QSystemTrayIcon::Trigger  )
    {
        this->showMaximized();
    }

}

//定时器槽函数
void Widget::m_time_out_monitor()
{
    int current_hour = QTime::currentTime().hour();
    int current_minute = QTime::currentTime().minute();
    QList<int> check_minute = {0,10,20,30};

    //最大化显示
        if(current_hour == 16 && check_minute.contains(current_minute))
    {
        if(this->isHidden() ||
           this->isMinimized())
        {

            this->showMaximized();

            //设置业务日期
            BusiDate m_date;
            ui->labelDate->setText(QString("业务日期：%1").arg(m_date.getEndDate()));
        }
    }

    //发起监控
    emit start_check();
}

//初始化日志
void Widget::m_init_log()
{
    // 新建文件目录
    m_logdir = QDir::currentPath() + "/log";

    if (!QDir(m_logdir).exists())
    {
        QDir(m_logdir).mkpath(m_logdir);
    }
}

//日志写入函数
void Widget::m_write_log(const QString &logStr)
{
    //设置名字
    QString logFileName = QString("/log_%1.txt").arg(QDate::currentDate().toString("yyyyMMdd"));
    logFileName = m_logdir + logFileName;
    m_loger.setFileName(logFileName);
    m_loger.open(QIODevice::Text | QIODevice::Append );
    QTextStream out(&m_loger);
    out.setCodec(QTextCodec::codecForName("utf-8"));
    QString logString = QString("[%1]：%2%3")
            .arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"),logStr,"\n");
    out << logString;
    m_loger.close();
}

//请求错误处理
void Widget::m_handleWorkerError(const QString &errorStr)
{
    QMessageBox::warning(this,"错误信息",errorStr,"确  定");
}



